package com.zj.study.utils;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import lombok.Data;
import lombok.experimental.Accessors;
import org.json.JSONObject;
import org.json.XML;

/**
 * @author 赵赳
 * @since 2022/9/6 13:53
 */
public class XmlUtils {

  // 头部追加 <?xml version="1.0" encoding="UTF-8"?>
  final static String HEAD = "<xml>";
  final static String END = "</xml>";

  // abc标签后追加 locale=" zh_CN"
  final static String BLANK = " ";
  final static String ADD_STR = "locale=\"zh_CN\"";

  /**
   * xml字符串转json
   *
   * @param xmlStr xml字符串
   * @return json
   */
  public static String xmlToJson(String xmlStr) {
    var replace = xmlStr.replace("<xml>", "").replace("</xml>", "");
    JSONObject jsonObject = XML.toJSONObject(replace);
    return jsonObject.toString();
  }

  /**
   * json转xml字符串
   *
   * @param jsonStr json字符串
   * @return xml字符串
   */
  public static String jsonToXml(String jsonStr) {
    JSONObject jsonObject = new JSONObject(jsonStr);
    String xmlStr = XML.toString(jsonObject);
    // abc标签后追加ADD_STR
    String abc = appendXmlTagCon(xmlStr, "abc", ADD_STR);
    return HEAD + abc + END;
  }

  public static String appendXmlTagCon(String xmlStr, String tagStr, String appendStr) {
    // 计算标签出现的起始位置
    int begin = xmlStr.indexOf(tagStr);
    if (begin < 0) {
      // 未出现该字符串 返回原报文
      return xmlStr;
    }
    // 计算追加字符串时的起始位置
    int i = begin + tagStr.length();
    // 插入追加的字符串
    StringBuilder builder = new StringBuilder(xmlStr).insert(i, BLANK + appendStr);
    return builder + "";
  }

  public static void main(String[] args) {
    //var employee = new Employee().setAge(30).setName("Tom").setTechnology("Java");
    //var jsonStr = com.alibaba.fastjson.JSONObject.toJSONString(employee);
    //System.out.println("jsonStr = " + jsonStr);
    //var toXml = XmlUtils.jsonToXml(jsonStr);
    //System.out.println("toXml = " + toXml);
    //
    //var toJson = XmlUtils.xmlToJson(toXml);
    //System.out.println("toJson = " + toJson);
    //
    //var bean = com.alibaba.fastjson.JSONObject.parseObject(toJson, Employee.class);
    //System.out.println("employee1 = " + bean);

    String endDate = "20220916";
    String endTime = "113213";

    var finishTime = endDate + endTime;
    System.out.println("finishTime = " + finishTime);

    var formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    var localDateTime = LocalDateTime.parse(finishTime, formatter);
    System.out.println("localDateTime = " + localDateTime);


  }

  @Data
  @Accessors(chain = true)
  static class Employee {

    private Integer age;
    private String name;
    private String technology;
  }
}
